$(function(){
//	loadIframe($("#mapDiv"),"baseMapTrack3Formal.html");
	var pagePath = $("#pagePath").val();
	//点击查询
	$("#search").click(function(){
		var taskId=$("div.dropdown-list[data-name='taskId']").find("a").attr("id");
		var taskName = $.trim($("#taskName").val());
		var lineId = $("#lineDiv").children().attr("id");
		var begTime = $("#begTime").val();
		var endTime = $("#endTime").val();
		var segmentId = $("#segmentDiv").children().attr("id");
		if("" == taskId || "jcrwmc" == taskId || undefined == taskId){
			taskId = "";
		}
		if("" == lineId || "gdmc" == lineId || undefined == lineId){
			lineId = "";
		}
		if("" == segmentId || "jcgdmc" == segmentId || undefined == segmentId){
			segmentId = "";
		}
		$("#taskNameHiddenId").val(taskId);
		$("#lineHiddenId").val(lineId);
		$("#begTimeHiddenId").val(begTime);
		$("#endTimeHiddenId").val(endTime); 
		$("#segmentHiddenId").val(segmentId);
		
		var data={"taskName":taskName,"lineId":lineId,"begTime":begTime,"endTime":endTime,"segmentId":segmentId}
		var map={"fillDiv":"#searchBody",
	              "url":""+pagePath+"/insp/inspTaskTrack/findByCondition.json"};
	    searchPage(map,data);
	});
	
	/* 日期格式化 */
	Date.prototype.Format = function(fmt) {
        var o = {
            "M+" : this.getMonth() + 1, //月份
            "d+" : this.getDate(), //日
            "h+" : this.getHours(), //小时
            "m+" : this.getMinutes(), //分
            "s+" : this.getSeconds(), //秒
            "q+" : Math.floor((this.getMonth() + 3) / 3), //季度
            "S" : this.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")
                    .substr(4 - RegExp.$1.length));
        for ( var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1,
                        (RegExp.$1.length == 1) ? (o[k])
                                : (("00" + o[k])
                                .substr(("" + o[k]).length)));
        return fmt;
    }
	
	
	
});

/**
 * 分页
 * @param current
 * @param pageCount
 * @param totalSize
 */
function commonPages(map){
    $("#commonsPage").createPage({
        current:parseInt(map.current),
        pageCount:parseInt(map.pageCount),
        totalSize:parseInt(map.totalSize),
        url:map.url,
        fillDiv:map.fillDiv,
        backFn:function(current,pageCount,totalSize,url,fillDiv){
            var resultMap={"current":parseInt(current),"isPage":"isPage","url":url,"fillDiv":fillDiv};
            var data={};
            searchPage(resultMap,data);
        }
    })
}

function searchPage(map,data){
	//获取隐藏域的值
	var taskName = $("#taskNameHiddenId").val();
	var lineId = $("#lineHiddenId").val();
	var begTime = $("#begTimeHiddenId").val();
	var endTime = $("#endTimeHiddenId").val();
	var segmentId = $("#segmentHiddenId").val();
	
	if(lineId == "gdmc" || lineId == ""){
		lineId = "";
	}
	if(segmentId == "jcgdmc" || segmentId == ""){
		segmentId = "";
	}
    var isPage=map.isPage;
    var current=1;
    if("isPage"==isPage){
        current=parseInt(map.current)
    }else{
        current=1;
    }
    var pageCount=$("#pageSelect").val();
    data.pageCount=parseInt(pageCount);
    data.current=current;
    //参数注入
    data.taskId = taskName;
    data.lineId = lineId;
    data.begTime = begTime;
    data.endTime = endTime;
    data.segmentId = segmentId;
    $.ajax({
        url:map.url,
        type:"post",
        dataType:"json",
        data:data,
        success:function(d){
            var p= d.main;
            if(p.length==0){
            	//如果没有数据，添加图片隐藏分页
            	$("#searchBody").empty();
            	$("#noDataImg").removeClass('none')
            	$("#commonsPage").addClass('none')
            }else{
            	$("#noDataImg").addClass('none')
            	$("#commonsPage").removeClass('none')
            var html='';
            for(var i=0;i< p.length;i++){
                html+=createProHtml(p[i],i);
            }
            $(map.fillDiv).html(html);
            if("isPage"==isPage){
                $("#totalSize").html(d.pageTotal);
            }else{
                $("#commonsPage").unbind();
                var resultMap={"current":1,"pageCount":pageCount,"totalSize":d.pageTotal,"url":map.url,"fillDiv":map.fillDiv};
                commonPages(resultMap);
            }}
        }
    });
}



//构建查询结果
function createProHtml(ps,i){
	var resourcePath = $("#resourcePath").val();
	var html = "";
	var hangClass = 'ul-header bg-white';
    if(i%2 != 0){
        hangClass = 'ul-header bg-second';
    }
    var id = ps.ID;
    var taskName = (null != ps.TASKNAME && "" != $.trim(ps.TASKNAME) ? ps.TASKNAME : '-');
    var createDate = (null != ps.CREATEDATE && "" != $.trim(ps.CREATEDATE) ? new Date(ps.CREATEDATE).Format("yyyy-MM-dd") : '-');
    var createUser = (null != ps.CREATEUSER && "" != $.trim(ps.CREATEUSER) ? ps.CREATEUSER : '-');	
    var lineName = (null != ps.LINENAME && "" != $.trim(ps.LINENAME) ? ps.LINENAME : '-');
    var fromPigTime = (null != ps.FROMPIGTIME && "" != $.trim(ps.FROMPIGTIME) ? new Date(ps.FROMPIGTIME).Format("yyyy-MM-dd hh:mm:ss") : '-');
    var stausNum = 	ps.STAUS;
    var staus;
    if(stausNum =="1"){
    	staus = "未发布";
    }else if(stausNum =="2"){
    	staus = "已发布";
    }else if(stausNum =="3"){
    	staus = "进行中";
    }else if(stausNum =="4"){
    	staus = "已完成";
    }else{
    	staus = "-";
    }
    var fromPig = (null != ps.FROMPIG && "" != $.trim(ps.FROMPIG) ? ps.FROMPIG : '-');
    var toPig = (null != ps.TOPIG && "" != $.trim(ps.TOPIG) ? ps.TOPIG : '-');
    var dtool = (null != ps.DETECTIONTOOL && "" != $.trim(ps.DETECTIONTOOL) ? ps.DETECTIONTOOL : '-');
    
	html += "<div class='info-tr' id='"+id+"'>" +
			"<ul class='"+ hangClass +"'>" +
				//"<li class='w5'><span class='Check-Box'><input id="+ id+" class="+id+" type='checkbox' name='childSelect'/></span></li>" +
				"<li class='w20'>"+taskName +"</li>" +
				"<li class='w10'>"+createDate+"</li>" +
				"<li class='w10'>"+createUser+"</li>" +
				"<li class='w20'>"+lineName +"</li>" +
				"<li class='w15'>"+fromPigTime +"</li>" +
				"<li class='w10'>"+ staus +"</li>" +
				"<li class='w15 no-right'>" +
					"<a href='javascript:;' onclick='trackFun(\""+id+"\");'  class='delet'><img src='"+resourcePath+"/images/comm/del.png' alt=''/></a>" +
					"<a href='javascript:;' onclick='monitorFun(\""+id+"\");'  class='public'><img src='"+resourcePath+"/images/comm/icon1_07.png' alt=''/></a>" +
				"</li>" +
				"<input type='hidden' value='"+fromPig+"' />" +
				"<input type='hidden' value='"+toPig+"' />" +
				"<input type='hidden' value='"+dtool+"' />" +
			"</ul>" +
		 "</div>";
	return html;
}

//检测任务跟踪
function trackFun(taskId){
	var pagePath = $("#pagePath").val();
	var url = pagePath+"/insp/inspTaskTrack/trackFun.json";
	var hangClass ="";
	$("#exportForm").children().attr("value",taskId);
	$("#trackTaskId").val(taskId);
	$("#importFile").val("");
	//构建追踪的顶部数据
	$("#trackName").val($("#"+taskId).find("li")[0].innerText);
	$("#trackPipeLineName").val($("#"+taskId).find("li")[3].innerText);
	$("#trackFromPig").val($("#"+taskId).find("input")[0].value);
	$("#trackToPig").val($("#"+taskId).find("input")[1].value);
	$("#trackTool").val($("#"+taskId).find("input")[2].value);
	$.ajax({
		url:url,
		type:'post',
		dataType:'json',
		data:{"taskId":taskId},
		success:function(data){
			if(data.praError == 1){
				alert("响应超时，请刷新页面后重试");
				return;
			}
			var dataList = data.inspTaskPoint;
			//构建跟踪点列表头
			var html="";
			$("#trackPointDiv").html('');
			html += "<div class='Popup_table'>" +
			"<div class='info-header clearFix'>" +
			"<ul class='ul-header'>" +
			"<li style='width:86px;'>MARK点编号</li>" +
			"<li class='w150'>最近参考点</li>" +
			"<li style='width:80px;'>通过时间</li>" +
			"<li style='width:80px;'>记录人</li>" +
			"<li class='w150'>备注</li>" +
			"</ul>";
			$.each(dataList,function(i,evalue){
				if(i%2 != 0){
				     hangClass = 'ul-header bg-second';
				 }else{
					 hangClass = 'ul-header bg-white';
				 }
				//遍历获取通过mark点的列表
				 html += "<div class='info-tr'>" +
				 	"<ul class='"+hangClass+"'>" +
				 		//mark编号
				 		"<li style='width:86px;'>"+((evalue.CODE == null || evalue.CODE == '') ? '-':evalue.CODE)+"</li>" +
				 		//参考点
				 		"<li class='w150'>"+evalue.REFERENCE+"</li>" +
				 		//通过记录时间
				 		"<li style='width:80px;'>"+((evalue.PASSTIME == null || evalue.PASSTIME == '') ? '-': new Date(evalue.PASSTIME).Format("yyyy-MM-dd hh:mm:ss"))+"</li>" +
				 		//记录人
				 		"<li style='width:80px;'>"+((evalue.RECRDER == null || evalue.RECRDER == '') ? '-':evalue.RECRDER)+"</li>" +
				 		//备注
				 		"<li class='w150'>"+((evalue.REMARK == null || evalue.REMARK == '') ? '-':evalue.REMARK)+"</li>" +
				 	"</ul>" +
				 "</div>";
			});
			html+="</div></div>";
			$("#trackPointDiv").html(html);
			
			//显示追踪
			$("#track").modal("show");
		}
	});
}

//获取检测管段
function getInspSegment(lineId){
	$("#inspSegment").html('');
	var pagePath = $("#pagePath").val();
	var url = pagePath + "/insp/inspTaskManager/getInspSegment.json";
	$.ajax({
		url:url,
		type:'post',
		dataType:'json',
		data:{"lineId":lineId},
		success:function(d){
			var inspSegment = d.segment;
			var html='';
			$.each(inspSegment,function(i,evalue){
				html += "<li><a href='javascript:void(0);' id='"+ evalue.ID+"'>"+ evalue.NAME+"</a></li>";
			});
			$("#segmentDiv").html("<a href='javascript:void(0);' id='jcgdmc'>检测管段名称</a><span></span>");
			$("#inspSegment").html(html);
			$("#inspSegment a").click(function(){
				//查询检测任务
				resultAjax(getJsPath()+"../insp/metalLoss/task.json","taskSegmentId="+$(this).attr("id"),parseTask,"JSON");
				
			});
			resetTask();
		}
	});
}
//重置task 选项
function resetTask()
{
	var baseSelect = $(".selectTask").parent().find(".drop-list-min a");
	baseSelect.html("检测任务名称");
	baseSelect.removeAttr("id");
	$(".selectTask").empty();
}

//导出追踪点
function exportTrackPoint(){
	$("input[name='taskId']").val($("#trackTaskId").val());
	if($("input[name='taskId']") == ""){
		alert("操作超时，请刷新页面重试");
		return ;
	}
	$("#exportForm").submit();
}
//导入跟踪点
function fileUpload(){
	var pagePath = $("#pagePath").val();
	var url = pagePath+"/insp/inspTaskTrack/importTrackPoint.json";
	//任务uId
	var taskId = $("#trackTaskId").val();
	$.ajaxFileUpload({
		url:url,
		fileElementId:"importFile",
		dataType:"json",
		secureuri:false,
		data:{"taskId":taskId},
		success:function(data){
			var msgCode = data.msgCode;
			if(msgCode =="2"){
				alert("请选择excel格式文件");
			}else if(msgCode == "3"){
				alert("所选文件过大，请重新选择");
			}else if(msgCode == "taskError"){
				alert("导入文件与任务关联不匹配，请重新选择");
			}else if(msgCode == "4"){
				alert("上传文件与原导出文件不匹配");
			}else if(msgCode == "5"){
				alert("上传文件与原导出文件不匹配");
			}else if(msgCode == "6"){
				alert("不允许修改文件ID的值");
			}else if(msgCode == "7"){
				alert("请填写有效的通过时间,格式为年/月/日 时:分:秒(xxxx/xx/xx 00:00:00)");
			}else if(msgCode == "cellNull"){
				alert("excel数据出现空值，请检查。");
			}else if(data.msgcode == "successful"){
				alert("操作成功");
//				window.location.href = pagePath + "/insp/inspTaskTrack/getInspTaskTrackIndex.html";
			}
		}
	});
}

function saveTaskTrack(){
	var saveflag = window.confirm("请确保跟踪点已经导入，确定要保存吗?");
	if(saveflag){
		var pagePath = $("#pagePath").val();
		var url = pagePath+"/insp/inspTaskTrack/saveTaskTrack.json";
		var taskId = $("#trackTaskId").val();
		$.ajax({
			url:url,
			type:'post',
			dataType:'json',
			data:{"taskId":taskId},
			success:function(data){
				var code = data.msgCode;
				if(code != null && code != ""){
					alert("保存成功");
					window.location.href = pagePath + "/insp/inspTaskTrack/getInspTaskTrackIndex.html";
				}
			}
		});
	}
}

//检测任务监控
/**
 * 页面初始化时需传数据格式。piggingstructure:收发球的json数组 ，marker：通过点的gisId
 * [{typeName:"piggingstructure",gisIdArray:[12,13,14]},{typeName:"marker",gisIdArray:[18,19,20]}]
 */
function monitorFun(taskId){
	$("#monitorTaskId").val(taskId);
//	$("#monitorFromPig").val($("#"+taskId).find("input")[0].value);
//	$("#monitorToPig").val($("#"+taskId).find("input")[1].value);
//	$("#monitorTaskName").val($("#"+taskId).find("li")[0].innerText);
	$("#monitorTaskName").html("任务名为：【 "+$("#"+taskId).find("li")[0].innerText + " 】的监控");
	var pagePath = $("#pagePath").val();
	var gisResourcePath = $("#gisResourcePath").val();
	var url = pagePath+"/insp/inspTaskTrack/monitorFun.json";
	$.ajax({
		url:url,
		type:'post',
		dataType:'json',
		data:{"taskId":taskId},
		success:function(data){
			var gisArray = new Array();
			//收发球点
			var piggingstructure = "["+data.piggingstructure.fromPig +","+ data.piggingstructure.toPig+"]";
			//gisId
			if(data.gis[0]!=null)
			{
			var d = data.gis;
			 $.each(d,function(i,evalue){
    			 var value = d[i].GISID;
    			 gisArray.push(value);
    		 });
			}
			 var gisStr = "["+gisArray.join()+"]";
			var gisIdJsonArray = "[{typeName:'piggingstructure',gisIdArray:"+piggingstructure+"},{typeName:'marker',gisIdArray:"+gisStr +"}]";

			$("#frameId").attr("src",gisResourcePath + "/baseMapTrack3Formal.jsp?gisIdJsonArray="+gisIdJsonArray);
//			document.getElementById("dyMap").contentWindow.showAllPoints(gisIdJsonArray);
			//显示监控
			$("#monitor").modal("show");
		}
	});
}

//获取任务的收发点
function getPigByTaskId(taskId){
	var pagePath = $("#pagePath").val();
	var url = pagePath+"/insp/inspTaskTrack/getPigByTaskId.json";
	$.ajax({
		url:url,
		type:'post',
		dataType:'json',
		data:{"taskId":taskId},
		success:function(data){
			$("#monitorFromPig").val("");
			$("#monitorToPig").val("");
			var dataList = data.pigs;
			if(dataList.length == 1){
				$.each(dataList,function(i,evalue){
					$("#monitorFromPig").val(evalue.FROMSTR);
					$("#monitorToPig").val(evalue.TOSTR);
					
				});
			}
		}
	});
}


function startMonitor(){
	var taskId = $("#monitorTaskId").val();
	alert(taskId);
}



function noPermitInput(e){    
    var evt = window.event || e ;  
     if(isIE()){  
         evt.returnValue=false; //ie 禁止键盘输入  
         $("#begTime").val("");
     }else{  
         evt.preventDefault(); //fire fox 禁止键盘输入  
         $("#endTime").val("");
     }     
}  
function isIE() {  
 if (window.navigator.userAgent.toLowerCase().indexOf("msie") >= 1)  
     return true;  
 else  
     return false;  
}   